package com.netty.coder;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;

public class StringDecoder extends ByteToMessageDecoder<String> {

	@Override
	public String decode(ChannelHandlerContext ctx, ByteBuf in)
			throws Exception {
	
		if (in.readableBytes() < 4) {
            return null;
        }
		
        in.markReaderIndex();

        int dataLength = in.readInt();
        if (in.readableBytes() < dataLength) {
            in.resetReaderIndex();
            return null;
        }
        
        String msg = "";
        
        if (dataLength>=0)
        {   
	        byte[] bytes = new byte[dataLength];	        
        
	        in.readBytes(bytes);        
	        
	        
			try {				
				msg = new String(bytes, "UTF-8");
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
        }
        return msg;
		
	}

}
